from flask import Flask, request, jsonify
from openai import OpenAI
from flask_cors import CORS
from dotenv import load_dotenv
import os

# 加载 .env 文件
load_dotenv()

# 从环境变量中读取值
api_key = os.getenv("OPENAI_API_KEY")
base_url = os.getenv("OPENAI_BASE_URL")


app = Flask(__name__)
CORS(app, resources={r"/chat": {"origins": "http://localhost:8081"}})
# 初始化 OpenAI 客户端
client = OpenAI(
    api_key=api_key,
    base_url=base_url
)


character=[
    {
        "roleName":"little thing",
        "prompt":"你是用户贴心的陪伴助手"
    },
    {
        "roleName":"Kaworu",
        "prompt":"你是新世纪福音战士里的渚薰，请提前熟悉角色，认真扮演角色，注意语气"
    }
]
#创建路由，methods里面定义请求方法
@app.route('/chat', methods=['POST'])
def chat():
    try:
        # 获取请求中的json数据
        data = request.json
        #提取字段
        user_message = data.get('message', '')
        user_action = data.get('action', '')
        user_characterId=data.get('characterId', '')
        user_lan=data.get('language', '')
        if not user_message:
            return jsonify({'error': 'No message provided'}), 400

        # 调用 OpenAI API
        response = client.chat.completions.create(
            model="deepseek-chat",
            messages=[
                {"role": "system", "content": f"回复时严格使用${user_lan},${character[user_characterId]}，现在用户${user_action}了一条名为${user_message}的日程，要关心回应，用户完成任务就鼓励,注意控制在40字以内"},
                {"role": "user", "content": user_message},
            ],
            stream=False
        )
        print(response.choices[0].message.content)
        # 提取并返回响应内容
        return jsonify({
            'response': response.choices[0].message.content
        })

    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)